package com.stool.minivideo.controller;

import com.stool.minivideo.config.ResourceConfig;
import com.stool.minivideo.enums.VideoStatusEnum;
import com.stool.minivideo.pojo.Bgm;
import com.stool.minivideo.pojo.Comment;
import com.stool.minivideo.pojo.User;
import com.stool.minivideo.pojo.Video;
import com.stool.minivideo.service.BgmService;
import com.stool.minivideo.service.VideoService;
import com.stool.minivideo.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@RestController
@Api(value = "视频相关业务的接口", tags = {"视频相关业务的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController{

    @Autowired
    private BgmService bgmService;

    @Autowired
    private VideoService videoService;

    @Autowired
    private ResourceConfig resourceConfig;

    @ApiOperation(value = "上传视频", notes = "上传视频的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "bgmId", value = "背景音乐id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "videoSeconds", value = "播放长度", required = true, paramType = "form"),
            @ApiImplicitParam(name = "videoWidth", value = "视频宽度", required = true, paramType = "form"),
            @ApiImplicitParam(name = "videoHeight", value = "视频高度", required = true, paramType = "form"),
            @ApiImplicitParam(name = "desc", value = "视频描述", required = false, paramType = "form"),
    })
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public MinivideoJSONResult upload(String userId,
                                          String bgmId,
                                          double videoSeconds,
                                          int videoWidth,
                                          int videoHeight,
                                          String desc,
                                          @ApiParam(value = "短视频", required = true)
                                          MultipartFile file) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return MinivideoJSONResult.errorMsg("用户id不能为空...");
        }

        // 保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/video";

        String coverPathDB = "/" + userId + "/video";
        String videoName = UUID.randomUUID().toString() + ".mp4";
        // 文件上传的最终保存路径
        String finalVideoPath = resourceConfig.getFileSpace() + uploadPathDB + "/" + videoName;

        if (uploadFile(finalVideoPath, file)) {

            // 得到.之前的字符串
            String filenamePrefix = videoName.split("\\.")[0];
            coverPathDB = coverPathDB + "/" + filenamePrefix + ".jpg";

            // 设置数据库保存的路径
            uploadPathDB += ("/" + videoName);

            // 判断bgmId是否为空，如果不为空，那就查询bgm的信息，并且合并视频，生产新的视频
            if (StringUtils.isNotBlank(bgmId)) {
                Bgm bgm = bgmService.queryBgmById(bgmId);
                String mp3InputPath = resourceConfig.getFileSpace() + bgm.getPath();

//                MergeVideoMp3 tool = new MergeVideoMp3(resourceConfig.getFfmpegEXE());
                String videoInputPath = finalVideoPath;

                String videoOutputName = UUID.randomUUID().toString() + ".mp4";
                uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName;
                finalVideoPath = resourceConfig.getFileSpace() + uploadPathDB;
                VideoUtils.mergeVideoMp3(resourceConfig.getFfmpegEXE(), videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
//                tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
            }

            // 对视频进行截图
//            FetchVideoCover fetchVideoCover = new FetchVideoCover(resourceConfig.getFfmpegEXE());
//            fetchVideoCover.getCover(finalVideoPath, resourceConfig.getFileSpace()  + coverPathDB);
            VideoUtils.fetchVideoCover(resourceConfig.getFfmpegEXE(), finalVideoPath, resourceConfig.getFileSpace()  + coverPathDB);

            // 保存视频信息到数据库
            Video video = new Video();
            video.setAudioId(bgmId);
            video.setUserId(userId);
            video.setVideoSeconds((float)videoSeconds);
            video.setVideoHeight(videoHeight);
            video.setVideoWidth(videoWidth);
            video.setVideoDesc(desc);
            video.setVideoPath(uploadPathDB);
            video.setStatus(VideoStatusEnum.SUCCESS.value);
            video.setCreateTime(new Date());
            video.setCoverPath(coverPathDB);

            String videoId = videoService.saveVideo(video);

            return MinivideoJSONResult.ok(videoId);
        } else {
            return MinivideoJSONResult.errorMsg("上传出错...");
        }
    }

    @ApiOperation(value = "上传封面", notes = "上传封面的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "videoId", value = "视频主键id", required = true),
    })
    @PostMapping(value = "/uploadCover", headers = "content-type=multipart/form-data")
    public MinivideoJSONResult uploadCover(String userId,
                                           String videoId,
                                           @ApiParam(value = "视频封面", required = true)
                                           MultipartFile file) throws Exception {
        if (StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) {
            return MinivideoJSONResult.errorMsg("视频主键id和用户id不能为空...");
        }

        // 保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/video";
        String filePath = resourceConfig.getFileSpace() + uploadPathDB + "/" + file.getOriginalFilename();
        if (uploadFile(filePath, file)) {
            uploadPathDB = uploadPathDB + "/" + file.getOriginalFilename();
            videoService.updateVideo(videoId, uploadPathDB);
            return MinivideoJSONResult.ok();
        } else {
            return MinivideoJSONResult.errorMsg("上传失败...");
        }

    }

    /**
     * @Description: 分页和搜索查询视频列表
     * @param video
     * @param isSaveRecord 1 - 需要保存；0 - 不需要保存，或者为空的时候
     * @param page
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/showAll")
    public MinivideoJSONResult showAll(@RequestBody Video video,
                                       Integer isSaveRecord,
                                       Integer page) throws Exception {
        if (page == null) {
            page = 1;
        }

        PagedResult result = videoService.getAllVideos(video, isSaveRecord, page, PAGE_SIZE);
        return MinivideoJSONResult.ok(result);
    }

    @PostMapping(value = "/hot")
    public MinivideoJSONResult hot() throws Exception {
        return MinivideoJSONResult.ok(videoService.getHotwords());
    }

    @PostMapping(value = "/userLike")
    public MinivideoJSONResult userLike(String userId, String videoId, String videoCreaterId) throws Exception {
        videoService.userLikeVideo(userId, videoId, videoCreaterId);
        return MinivideoJSONResult.ok();
    }

    @PostMapping(value = "/userUnlike")
    public MinivideoJSONResult userUnlike(String userId, String videoId, String videoCreaterId) throws Exception {
        videoService.userUnlikeVideo(userId, videoId, videoCreaterId);
        return MinivideoJSONResult.ok();
    }

    /**
     * 我关注的人发的视频
     * @param userId
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    @PostMapping("/showMyFollow")
    public MinivideoJSONResult showMyFollow(String userId, Integer page, Integer pageSize) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return MinivideoJSONResult.ok();
        }

        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 6;
        }

        PagedResult videoList = videoService.queryMyFollowVideos(userId, page, pageSize);

        return MinivideoJSONResult.ok(videoList);
    }

    /**
     * 我收藏过的视频列表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    @PostMapping("/showMyLike")
    public MinivideoJSONResult showMyLike(String userId, Integer page, Integer pageSize) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return MinivideoJSONResult.ok();
        }

        if (page == null) {
            page = 1;
        }

        if (pageSize == null) {
            pageSize = 6;
        }

        PagedResult videoList = videoService.queryMyLikeVideos(userId, page, pageSize);

        return MinivideoJSONResult.ok(videoList);
    }

    @PostMapping("/saveComment")
    public MinivideoJSONResult saveComment(@RequestBody Comment comment, String fatherCommentId, String toUserId) throws Exception {
        comment.setFatherCommentId(fatherCommentId);
        comment.setToUserId(toUserId);
        videoService.saveComment(comment);
        return MinivideoJSONResult.ok();
    }

    @PostMapping("/getVideoComments")
    public MinivideoJSONResult getVideoComments(String videoId, Integer page, Integer pageSize) throws Exception{
        if (StringUtils.isBlank(videoId)) {
            return MinivideoJSONResult.ok();
        }

        // 分页查询视频列表，时间顺序倒序排序
        if (page == null) {
            page = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        PagedResult list = videoService.getAllComments(videoId, page, pageSize);

        return MinivideoJSONResult.ok(list);
    }
}
